<?php

class LangBehavior extends ModelBehavior {


	public function setup(Model $Model, $config = array()) {
		// print_r($Model);
	}

/**
 * Cleanup Callback unbinds bound translations and deletes setting information.
 *
 * @param Model $Model Model being detached.
 * @return void
 */
	public function cleanup(Model $Model) {
		// $this->unbindTranslation($Model);
		// unset($this->settings[$Model->alias]);
		// unset($this->runtime[$Model->alias]);
	}

/**
 * beforeFind Callback
 *
 * @param Model $Model Model find is being run on.
 * @param array $query Array of Query parameters.
 * @return array Modified query
 */
	public function beforeFind(Model $Model, $query) {
		$query["recursive"]=1;
		// print_r($query);
		return $query;
	}




/**
 * afterFind Callback
 *
 * @param Model $Model Model find was run on
 * @param array $results Array of model results.
 * @param boolean $primary Did the find originate on $model.
 * @return array Modified results
 */
	public function afterFind(Model $Model, $results, $primary) {
		// print_r($results);
		//campi da escludere nella traduzione
		$campiDaIgnorare=array('id','reference_id','locale');
		foreach ($results as $key => $value) {
			// print_r($value[$Model->alias."Lang"]);
			//ciclo l'array riferita alla tabella Lang
			if (isset($value[$Model->alias."Lang"])) {
				foreach ($value[$Model->alias."Lang"] as $keyLangTable => $langTable) {
					//imposto come chiave della tabella la lingua il cui record fa riferimento, più semplice poi gestirlo lato view
					$results[$key][$Model->alias."Lang"][$langTable["locale"]]=$langTable;
					//elimino la chiave precedentemente sostituita con il codice locale
					unset($results[$key][$Model->alias."Lang"][$keyLangTable]);
					//ciclo tutti i campi della tabella per aggiornare la lingua
					// print_r($results[$key][$Model->alias."Lang"][$langTable["locale"]]);
					if (Configure::read("Config.language")==$langTable["locale"]) {
						foreach ($results[$key][$Model->alias."Lang"][$langTable["locale"]] as $field => $fieldValue) {
							if (!in_array($field, $campiDaIgnorare)) {
								// print_r($value);
								$results[$key][$Model->alias][$field]=$fieldValue;
							}
						}
					}
				}
			}
		}
		// print_r($results);
		return $results;
	}

/**
 * beforeValidate Callback
 *
 * @param Model $Model Model invalidFields was called on.
 * @return boolean
 */
	public function beforeValidate(Model $Model) {

		return true;
	}

/**
 * beforeSave callback.
 *
 * @param Model $Model Model save was called on.
 * @return boolean true.
 */
	public function beforeSave(Model $Model, $options = array()) {
		// print_r($Model->data);
		// print_r($options);
		return true;
	}


/**
 * afterSave Callback
 *
 * @param Model $Model Model the callback is called on
 * @param boolean $created Whether or not the save created a record.
 * @return void
 */
	public function afterSave(Model $Model, $created) {
		try {
			// print_r($Model->data["ita"]);
			// print_r($created);
			/* salvo i dati nella tabella gestita dal model aliasLang
			 * i dati devono avere la seguente struttura:
			 * Array([ita] => array ([campo1] => valore,[campo2]=>valore))
			*/
			$modelName = $Model->alias."Lang";
		    $this->loadModel($modelName); // carico il model che gestisce le lingue
		    // pr($Model->data);die;
		    foreach ($Model->data[$modelName]["ita"] as $campo => $valore) {
		    	// print_r($campo)
				$this->{$modelName}->set($campo,htmlspecialchars($valore, ENT_QUOTES));
			}
		    // $this->{$modelName}->set($Model->data["ita"]);
			$this->{$modelName}->set("locale","ita");
			$this->{$modelName}->set("reference_id",$Model->id);
			// $this->{$modelName}->set("testo",htmlspecialchars($this->request->data["ita"]["HelpLang"]["testo_non_codificato"], ENT_QUOTES));
		    $this->{$modelName}->save();
	
		    if (!isset($Model->data[$modelName]["eng"]["id"]) || empty($Model->data[$modelName]["eng"]["id"])) {
		    	$this->{$modelName}->create();
			    // $this->{$modelName}->set($Model->data["eng"]);
				$this->{$modelName}->set("locale","eng");
				$this->{$modelName}->set("reference_id",$Model->id);
		    // } else {
			    // $this->{$modelName}->set($Model->data["eng"]);
		    }
		    foreach ($Model->data[$modelName]["eng"] as $campo => $valore) {
		    	// print_r($campo)
				$this->{$modelName}->set($campo,htmlspecialchars($valore, ENT_QUOTES));
			}
		    $this->{$modelName}->save();
			return true;
		} catch (exception $e) {
			CakeLog::error($e->getMessage());
			throw $e;
			return false;
		}
	}

	private function loadModel($modelName)  {
	    App::import('Model',$modelName); //load model..
	    $this->{$modelName} = new $modelName(); //and create an instance of it
	}

/**
 * afterDelete Callback
 *
 * @param Model $Model Model the callback was run on.
 * @return void
 */
	public function afterDelete(Model $Model) {

	}

/**
 * Get selected locale for model
 *
 * @param Model $Model Model the locale needs to be set/get on.
 * @return mixed string or false
 */
	protected function _getLocale(Model $Model) {
		if (!isset($Model->locale) || is_null($Model->locale)) {
			$I18n = I18n::getInstance();
			$I18n->l10n->get(Configure::read('Config.language'));
			$Model->locale = $I18n->l10n->locale;
		}

		return $Model->locale;
	}

	public function pippo() {
		return "pippo";
	}

}
